import json
import os
from pathlib import Path

STYLES_FILE = "styles.json"

# 默认风格
DEFAULT_STYLES = {
    "predefined": [
        {
            "name": "default",
            "description": "标准漫画风格",
            "params": {
                "line_weight": 2,
                "color_palette": "vibrant",
                "shading": "cel"
            }
        },
        {
            "name": "shonen",
            "description": "少年漫画风格",
            "params": {
                "line_weight": 3,
                "color_palette": "bold",
                "shading": "dynamic",
                "speed_lines": True
            }
        },
        {
            "name": "shoujo",
            "description": "少女漫画风格",
            "params": {
                "line_weight": 1,
                "color_palette": "pastel",
                "shading": "soft",
                "sparkles": True
            }
        }
    ],
    "custom": []
}


def load_styles():
    """加载风格配置"""
    if not Path(STYLES_FILE).exists():
        save_styles(DEFAULT_STYLES)
        return DEFAULT_STYLES

    try:
        with open(STYLES_FILE, 'r') as f:
            return json.load(f)
    except:
        return DEFAULT_STYLES


def save_styles(styles):
    """保存风格配置"""
    with open(STYLES_FILE, 'w') as f:
        json.dump(styles, f, indent=2)


def get_styles():
    """获取所有可用风格"""
    styles = load_styles()
    return {
        "predefined": styles["predefined"],
        "custom": styles["custom"]
    }


def save_custom_style(name, params):
    """保存自定义风格"""
    styles = load_styles()

    # 检查是否已存在
    for style in styles["custom"]:
        if style["name"].lower() == name.lower():
            return {"status": "error", "message": "风格名称已存在"}

    new_style = {
        "name": name,
        "description": f"自定义风格: {name}",
        "params": params
    }

    styles["custom"].append(new_style)
    save_styles(styles)

    return {"status": "success", "style": new_style}